package com.example.algorithm;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 日志日活月活统计
 *
 * @DATE 2024/7/7
 **/
public class IPData {

    public static void main(String[] args) {

    }

    // 获取月活，日活
    public static int[] getActiveUserNum(List<String> logs) {
        // key存当天，value存放IP，自动去重
        Map<Integer, Set<String>> activeIpMap = new HashMap<>();
        // 月活
        activeIpMap.put(0, new HashSet<>());
        for (String log : logs) {
            if (log.endsWith("fail") || !log.contains("login.do|success")) {
                continue;
            }
            Integer day = Integer.valueOf(log.substring(8, 10));
            String ip = getFormateIp(log);
            if (!activeIpMap.containsKey(day)) {
                activeIpMap.put(day, new HashSet<>());
            }

            // 日活
            activeIpMap.get(day).add(ip);
            // 月活
            activeIpMap.get(0).add(ip);
        }

        int[] res = new int[32];
        for (int i = 0; i < res.length; i++) {
            if (!activeIpMap.containsKey(i)) {
                continue;
            }
            res[i] = activeIpMap.get(i).size();
        }
        return res;
    }

    // 对IP地址格式化
    private static String getFormateIp(String log) {
        String[] infos = log.split("\\|");
        String[] ipNums = infos[1].split("\\.");
        String ip = "";
        for (int i = 0; i < ipNums.length; i++) {
            if (i == ipNums.length - 1) {
                ip += Integer.valueOf(ipNums[i]);
            } else {
                ip += Integer.valueOf(ipNums[i]) + ".";
            }
        }
        return ip;
    }
}
